"""
Canvas backend

This file implements a backend for Canvas by Instructure, an open-source LMS
used widely at many colleges and universities, at least in the US.

This file is part of polyglot.
"""

import decimal
import requests
from .support import (Backend, Course, CategoryGrade, AssignmentGrade)

class CanvasCourse(Course):
    def __init__(self, backend, data):
        self.backend = backend
        self.data = data

        self.id = str(data["id"])
        self.name = self.title = data["name"]
        self.code = self.teacher = data["course_code"]

        decimal.getcontext().prec = 4
        grade = decimal.Decimal(data["enrollments"][0]["computed_current_score"])
        self.grade_summary = grade / 100

    @property
    def grades(self):
        assignments = self.backend.session.get(self.backend.url("courses/{}/assignments".format(self.id)), params={
            "include": ["submission"]
        })

        """
        submissions = self.backend.session.get(self.backend.url("courses/{}/students/submissions".format(self.id)), params={
            "include": ["submission_comments"],
        })
        """

        grades = [AssignmentGrade(a["name"], a["submission"]["score"], a["points_possible"], "") for a in assignments.json()]

        return [CategoryGrade("General", 90.01, grades)]

    @property
    def tasks(self):
        return []

class CanvasBackend(Backend):
    Config = ["Token", "School"]

    def url(self, endpoint):
        return "https://{}/api/v1/{}".format(self.config["School"], endpoint)

    def login(self, config):
        self.config = config
        api_key = config["Password"]

        self.session.headers["Authorization"] = "Bearer {}".format(api_key)

        req = self.session.get(self.url("users/self"))
        return req.status_code == 200

    def fast_login(self, config):
        self.config = config
        api_key = config["Password"]
        self.session.headers["Authorization"] = "Bearer {}".format(api_key)

    @property
    def courses(self):
        req = self.session.get(self.url("courses"), params={
            "enrollment_type": "student",
            "state": "available",
            "include": ["total_scores"]
        })

        print(req)

        data = [i for i in req.json() if "name" in i]

        return list(map(lambda q: CanvasCourse(self, q), data))
